<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="编号" prop="code" label-width="42px">
       <HouseInput v-model="queryParams.code" type="house"/>
     <!--   <el-autocomplete popper-class="my-autocomplete" v-model="queryParams.code" :fetch-suggestions="querySearch"
          placeholder="商铺完整编号" @select="handleSelect" clearable>
          <i class="el-icon-edit el-input__icon" slot="suffix" @click="handleIconClick">
          </i>
          <template slot-scope="{ item }">
            <div class="name">编号：{{ item.value }}</div>
            <span class="addr">状态：{{ item.label }}</span>
          </template>
        </el-autocomplete> -->
      </el-form-item>

      <el-form-item label="使用状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请使用使用状态" clearable>
          <el-option v-for="dict in dict.type.zxwy_oos_state" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['asset:shops:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['asset:shops:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['asset:shops:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['asset:shops:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shopsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="完整编号" align="center" prop="code" />
      <el-table-column label="商业区" align="center" prop="downtownName" />
      <el-table-column label="楼栋" align="center" prop="buildingName" />
      <el-table-column label="楼层" align="center" prop="floor" />
      <el-table-column label="房号" align="center" prop="room" />
      <el-table-column label="占地面积" align="center" prop="floorArea" />
      <el-table-column label="使用面积" align="center" prop="useArea" />
      <el-table-column label="租金" align="center" prop="rentFree" />
      <el-table-column label="使用状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.zxwy_oos_state" :value="scope.row.state" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['asset:shops:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['asset:shops:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商铺信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="楼栋">
          <el-cascader :options="houseFloor" clearable v-model="selectedCascaderValue"
            @change="handleCascaderChange"></el-cascader>
        </el-form-item>

        <el-form-item label="房号" prop="room">
          <el-input v-model="form.room" placeholder="请输入房号" />
        </el-form-item>
        <el-form-item label="楼层" prop="floor">
          <el-input v-model="form.floor" placeholder="请输入商铺所属楼层" />
        </el-form-item>
        <el-form-item label="占地面积" prop="floorArea">
          <el-input v-model="form.floorArea" placeholder="请输入占地面积" />
        </el-form-item>
        <el-form-item label="使用面积" prop="useArea">
          <el-input v-model="form.useArea" placeholder="请输入使用面积" />
        </el-form-item>
        <el-form-item label="租金" prop="rentFree">
          <el-input v-model="form.rentFree" placeholder="请输入商铺租金" />
        </el-form-item>
        <el-form-item label="使用状态" prop="state">
          <el-select v-model="form.state" placeholder="请选择使用状态" disabled>
            <el-option v-for="dict in dict.type.zxwy_oos_state" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listShops,
    getShops,
    delShops,
    addShops,
    updateShops,
    getShopsByDid
  } from "@/api/asset/shops";
  import {
    listBuilding,
    getBuilding
  } from "@/api/asset/building";
  import {
    listDowntown,
    getDowntown
  } from "@/api/asset/downtown";
  import {
    listHirer,
    getHirer
  } from "@/api/hirer/hirer";

  export default {
    name: "Shops",
    dicts: ['zxwy_oos_state'],
    data() {
      return {
        //修改的级联数据收集
        selectLeverList:[],

        codeName: '',
        stateName: '',
        restaurants: [],
        state: '',
        selectList: [],
        //
        selectedCascaderValue: [],
        // 转换后的级联选项
        cascaderOptions: [],
        houseFloor: [],
        //商业区列表
        BuildingList: [],
        //楼栋列表
        DowntownList: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商铺信息表格数据
        shopsList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          code: null,
          state: null,
          buildingName: null,
          buildingId: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          room: [{
            required: true,
            message: "房间号，唯一不能为空",
            trigger: "blur"
          }],
          floor: [{
            required: true,
            message: "商铺所属楼层不能为空",
            trigger: "blur"
          }],
          floorArea: [{
            required: true,
            message: "占地面积不能为空",
            trigger: "blur"
          }],
          useArea: [{
            required: true,
            message: "使用面积不能为空",
            trigger: "blur"
          }],
          state: [{
            required: true,
            message: "使用状态不能为空",
            trigger: "change"
          }],
        }
      };
    },
    created() {
      this.getList();
      this.fetchData();
    },
    mounted() {
      this.restaurants = this.loadAll();
    },
    methods: {
      //完整编号code查询
      querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        if(!queryString){
          return cb([]);
        }else{
          cb(results);
        }
      },
      createFilter(queryString) {
        return (restaurant) => {
          return restaurant.value.toLowerCase().includes(queryString.toLowerCase());
        };
      },
      loadAll() {
        return this.selectList;
      },
      handleSelect(item) {
        console.log(item);
      },
      handleIconClick(ev) {
        console.log(ev);
      },

      //

      getSelectedCascaderValue() {
        return this.selectedCascaderValue;
      },
      handleCascaderChange(value) {
        // console.log('选中的级联值:', value);
        this.form.downtownId = value[0],
          this.form.buildingId = value[1]
      },
      fetchData() {
        // 获取商业区数据
        listDowntown(this.queryParams).then(response => {
          this.DowntownList = response.rows;
          this.processDowntownData();
        });
      },
      processDowntownData() {
        this.cascaderOptions = this.DowntownList.map(item => ({
          value: item.id,
          label: item.name,
          children: []
        }));

        listBuilding(this.queryParams).then(response => {
          this.BuildingList = response.rows;
          this.processBuildingData();
        });
      },
      processBuildingData() {
        this.BuildingList.forEach(building => {
          const downtown = this.cascaderOptions.find(item => item.value === building.downtownId);
          if (downtown) {
            downtown.children.push({
              value: building.id,
              label: building.name
            });
          }
        });

        // 可以将其设置为 el-cascader 的 options
        this.houseFloor = this.cascaderOptions;
        // console.log(this.houseFloor);
      },
      getList() {
        this.selectList = [];
        this.loading = true;
        listShops(this.queryParams).then(response => {
          this.shopsList = response.rows;
          // listShops(this.queryParams).then(response => {
            // this.shopsList = response.rows;
            //处理模糊查询完整编号
            for (let it of this.shopsList) {
              // this.codeName='编号：'+it.code
              this.codeName = it.code
              if (it.state == 0) {
                this.stateName = '空置'
              } else if (it.state == 1) {
                this.stateName = '出租'
              } else {
                this.stateName = '出售'
              }
              this.selectList.push({
                value: this.codeName,
                label: this.stateName
              })
            }
          // });
          this.total = response.total;
          this.loading = false;
        });

      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          room: null,
          code: null,
          floor: null,
          floorArea: null,
          useArea: null,
          rentFree: null,
          state: 0,
          downtownId: null,
          buildingId: null,
          remark: null,
          deleted: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.selectList = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加商铺信息";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getShops(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改商铺信息";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateShops(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addShops(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除商铺信息编号为"' + ids + '"的数据项？').then(function() {
          return delShops(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('asset/shops/export', {
          ...this.queryParams
        }, `shops_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style >
  .my-autocomplete {
    li {
      line-height: normal;
      padding: 7px;

      .name {
        text-overflow: ellipsis;
        overflow: hidden;
      }
      .addr {
        font-size: 12px;
        color: #b4b4b4;
      }

      .highlighted .addr {
        color: #ddd;
      }
    }
  }
</style>
